import socket, sys, threading, Queue
from time import gmtime, strftime

#PORT = 18001
PORT = 843

def sendPolicy() :
    conn = q.get()
    pol = q.get()
    pol += '\0'
    print strftime("%a, %d %b %Y %H:%M:%S GMT +0000", gmtime())
    print "policy :\n", pol
    print "conn", conn
    sent = conn.send(pol)
    print sent, "characters sent"
    conn.close()
    exit()


policySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
policySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
###############################
path = "../../flashpolicy.xml"
###############################
f = open(path, 'r')
policy = f.read(10001)
if (len(policy) > 10000) :
    raise exceptions.RuntimeError("File probably too large to be a policy file", path)
if "cross-domain-policy" not in policy :
    raise exceptions.RuntimeError("Invalid policy file", path)
f.close()

try :
    ############################
    policySocket.bind(('', PORT))
    ############################
except socket.error:
    print "Error socket bind(" + socket.gethostname() + " " + PORT + ")"
    sys.exit()

while 1:
    print "Listening on port", PORT
    policySocket.listen(10)
    con, addr = policySocket.accept()
    print "connection accepted from", addr

    # une file pour communiquer
    q = Queue.Queue()
    q.put(con)
    q.put(policy)
    
    t = threading.Thread(target = sendPolicy)
    t.start()
    t.join()
    
